import { isNil as _isNil } from 'lodash';
import { LvRouterLinkType } from '../types';

/**
 * 判断源数据是否是undefined、null、''
 * @param value 源数据
 */
export function isEmpty(value): boolean {
  return value === '' || _isNil(value);
}

/**
 * 路由跳转
 * @param router angular路由
 * @param link url
 */
export function routerNavigate(router, link: LvRouterLinkType): void {
  if (router) {
    if (typeof link === 'string') {
      router.navigate([link]);
    } else if (typeof link === 'object' && link.length) {
      if (link.length === 2) {
        router.navigate(link[0] as any[], link[1]);
      } else {
        router.navigate(link);
      }
    }
  } else {
    // eslint-disable-next-line no-console
    console.warn('menu.routerLink need import RouterModule.forRoot()');
  }
}

/**
 * 生成32位随机字符串
 */
export function generateId(): string {
  return 'xyxyxyxyxyxyxyxyxyxyxyxyxyxyxyxy'.replace(/[xy]/g, (c): string => {
    // tslint:disable-next-line
    const r = (Math.random() * 16) | 0;
    // tslint:disable-next-line
    const v = c === 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
}

export function typeConvert(value: number | string): string {
  if (typeof value === 'number') {
    return `${value}px`;
  }
  return value;
}

function compareVersions(v1: string, v2: string): number {
  const v1Parts = v1.split('.').map(Number);
  const v2Parts = v2.split('.').map(Number);

  for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
    const v1Part = v1Parts[i] || 0;
    const v2Part = v2Parts[i] || 0;

    if (v1Part > v2Part) {
      return 1;
    }
    if (v1Part < v2Part) {
      return -1;
    }
  }

  return 0;
}

export function isFirefoxBelowRecentVersions(recentVersion: string = '122.0', esrVersion: string = '115.0'): boolean {
  const { userAgent } = navigator;
  const firefoxMatch = userAgent.match(/Firefox\/(?<browserVersion>[0-9\\.]+)/);

  if (firefoxMatch) {
    const currentVersion = firefoxMatch[1];
    if (compareVersions(currentVersion, esrVersion) === 0) {
      return false;
    }
    if (compareVersions(currentVersion, recentVersion) === -1) {
      return true;
    }
  }

  return false;
}
